package com.mryan.ps_auth.translator;

import com.mryan.ps_common.entity.PSResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_auth.translator
 * @Author: Yan
 * @CreateTime: 2021-04-25 20:43
 * @Description: 异常翻译器
 */
@Slf4j
@Component
public class PSWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

	@Override
	public ResponseEntity translate(Exception e) throws Exception {
		//500异常
		ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
		PSResponse psResponse = new PSResponse();
		String message = "认证失败";

		log.error(message,e);

		if (e instanceof UnsupportedGrantTypeException){
			message = "不支持该认证类型";
			return status.body(psResponse.message(message));
		}
		if (e instanceof InvalidGrantException){
			if (StringUtils.containsIgnoreCase(e.getMessage(),"Invalid refresh token")){
				message = "refresh token无效";
				return status.body(psResponse.message(message));
			}
			if (StringUtils.containsIgnoreCase(e.getMessage(),"locked")){
				message = "用户账号已被锁定，请联系管理员";
				return status.body(psResponse.message(message));
			}
			message = "用户名或密码错误";
			return status.body(psResponse.message(message));
		}
		return status.body(psResponse.message(message));
	}
}
